
const res = require('express/lib/response');
const db = require('../db/index')
const utils = require('../utils/index')


async function getRouter(req, res) {
    return new Promise(async (resolve, reject) => {
        try {
            let sql = 'select id,parent_id AS parentId,path,name,component,redirect,meta,icon,title,isLink,isHide,isFull,isAffix,isKeepAlive,menuType,redirect from router_menu';
            let userRole = await utils.getUserRole(req, res);
            if (!userRole.userRole || userRole.userRole == null || userRole.userRole == 'null') {
                userRole.userRole = '';
            }
            // 角色权限
            let roles = userRole.userRole.split(',');
            let results = await new Promise((resolve, reject) => {
                db.query(sql, (err, results) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(results);
                    }
                });
            });
            let list = [...results], routerArr = [];
            let filterAsyncRoutes = (lists, parentId, pathView = "") => {
                let resArr = [], obj = {};
                lists.map((t) => {
                    let objs = { ...t };
                    try { objs.meta = JSON.parse(objs.meta); objs.meta = {}; } catch (err) { objs.meta = {}; }
                    objs.meta.title = objs.title;
                    objs.meta.icon = objs.icon;
                    objs.meta.isKeepAlive = objs.isKeepAlive === 0 ? false : true;
                    objs.meta.isLink = objs.isLink;
                    objs.meta.isHide = objs.isHide === 0 ? false : true;
                    objs.meta.isFull = objs.isFull === 0 ? false : true;
                    objs.meta.isAffix = objs.isAffix === 0 ? false : true;

                    //递归
                    if (objs.parentId == parentId) {
                        objs.path = objs.path;
                        obj = { ...objs, children: filterAsyncRoutes(list, objs.id, objs.path) };

                        //如果是总管理
                        if (userRole.user.admin == 1 || userRole.roleAdmin) { resArr.push(obj); }
                        else {
                            //只拿角色权限通过的
                            if (roles.some((role) => obj.id == role)) resArr.push(obj);
                        }
                    }
                });

                return resArr;
            };
            let routerMenu = filterAsyncRoutes(list, 0, "");
            resolve({ routerMenu })
        } catch (error) {
            res.status(500).send({ error: 'An error occurred' });
        }
    })
}

module.exports = {
    async reqMenu(req, res) {
        let { routerMenu } = await getRouter(req, res);
        res.send({ data: { routerMenu: routerMenu } })
    },
    async reqGetRolesList(req, res) {
        let obj = req.body;
        let sql = `SELECT id,name,roles,checked_roles AS checkedRoles,role_key AS roleKey,update_time AS updateTime,create_time AS createTime FROM roles WHERE 1=1`;
        sql = utils.setLike(sql, "name", obj.name);
        let { total } = await utils.getSum({ sql, name: "roles", res, req });
        sql = utils.pageSize(sql, obj.pageNum, obj.pageSize);
        db.query(sql, (err, results) => {
            if (err) res.cc(err)
            res.send({ data: { data: results, pageNum: obj.pageNum, pageSize: obj.pageSize, total: obj.name ? results.length : total } })
        })
    },
    async reqAddRoles(req, res) {
        let obj = req.body;
        await utils.existName({ sql: `SELECT id FROM roles WHERE role_key=?`, name: obj.roleKey, res, msg: "权限字符已存在！", req });
        let sql = `INSERT INTO roles(name,roles,role_key) VALUES (?,?,?)`
        db.query(sql, [obj.name, obj.roles, obj.roleKey], (err, results) => {
            if (err) res.cc(err)
            res.send({ code: 200, msg: '添加成功' })
        })
    },
    reqDeleteRoles(req, res) {
        let sql = `DELETE FROM roles WHERE id IN (?)`;
        const ids = req.body.id;
        db.query(sql, [ids], (err, results) => {
            if (err) return res.cc(err)
            res.send({ code: 200, msg: '删除成功' })
        })
    },
    reqEditRoles(req, res) {
        let sql = "UPDATE  roles SET roles=?,name=?,role_key=? WHERE id=?", obj = req.body;
        db.query(sql, [obj.roles, obj.name, obj.roleKey, obj.id], (err, results) => {
            if (err) return res.cc(err)
            res.send({ code: 200, msg: '修改成功' })
        })
    },
    reqGetRolesAll(req, res) {
        let sql = `SELECT id,name,roles,checked_roles AS checkedRoles,role_key AS roleKey FROM roles`;
        db.query(sql, (err, results) => {
            if (err) return res.cc(err)
            res.send({ code: 200, data: results })
        })
    },
    async reqGetUser(req, res) {
        let obj = req.body;
        let sql = `SELECT a.id AS id, name, status, roles_id AS rolesId, remark, admin, pwd, url, a.update_time AS updateTime, a.create_time AS createTime FROM user AS a WHERE 1=1 ORDER BY id ASC`;
        sql = utils.setLike(sql, "name", obj.name);
        let { total } = await utils.getSum({ sql, name: "roles", res, req });
        sql = utils.pageSize(sql, obj.pageNum, obj.pageSize);
        db.query(sql, (err, results) => {
            if (err) return res.cc(err)
            res.send({ data: { data: results, pageNum: obj.pageNum, pageSize: obj.pageSize, total: obj.name ? results.length : total } })
        })
    },
    async reqAddUser(req, res) {
        let sql = "INSERT INTO user(name,status,roles_id,remark,pwd,url) VALUES (?,?,?,?,?,?)", obj = req.body;
        await utils.existName({ sql: "SELECT id FROM user WHERE  name=?", name: obj.name, res, msg: "用户名已被使用！", req });
        db.query(sql, [obj.name, obj.status, obj.rolesId, obj.remark, obj.pwd, obj.url || ""], (err, results) => {
            if (err) return res.cc(err)
            res.send({ code: 200, msg: '新增成功' })
        })
    },
    async reqEditUser(req, res) {
        let sql = "UPDATE user SET name=?, status=?, pwd=?, roles_id=?, remark=?, url=? WHERE id=?";
        let obj = req.body;
        await utils.delPreImg({ id: obj.id, name: 'user', obj })
        db.query(sql, [obj.name, obj.status, obj.pwd, obj.rolesId, obj.remark, obj.url, obj.id], (err, results) => {
            if (err) return res.cc(err);
            res.send({ code: 200, msg: '修改成功' });
        });
    },
    reqDeleteUser(req, res) {
        const ids = req.body.id;

        // 遍历 id 数组
        for (let i = 0; i < ids.length; i++) {
            const id = ids[i];

            // 判断是否为 1
            if (id === 1) {
                return res.send({ code: 400, msg: '不能删除管理员' });
            }
        }

        let sql = `DELETE FROM user WHERE id IN (?)`;

        db.query(sql, [ids], (err, results) => {
            if (err) return res.cc(err);
            res.send({ code: 200, msg: '删除成功' });
        });
    },
    reqChangeUser(req, res) {
        let sql = `update user set ? where id=?`
        let { id, status } = req.body
        /*  if (id === 1) return res.send({ code: 200, msg: '不能对管理员进行操作' }) */
        db.query(sql, [{ status }, id], (err, resutls) => {
            if (err) return res.cc(err)
            res.send({ code: 200, msg: '修改成功' })
        })
    },
    async reqAddMenu(req, res) {
        try {
            let sql = 'insert into router_menu(parent_id,path,icon,isHide,isKeepAlive,name,menuType,redirect,title,isFull,component) values(?,?,?,?,?,?,?,?,?,?,?)';
            let obj = req.body;
            await utils.existName({ sql: "SELECT id FROM router_menu WHERE name=?", name: obj.name, res, msg: "页面名称已存在！！", req });
            db.query(sql, [obj.parentId, obj.path, obj.icon, obj.isHide, obj.isKeepAlive, obj.name, obj.menuType, obj.redirect, obj.title, obj.isFull, obj.component], (err, result) => {
                if (err) {
                    console.error(err);
                    res.status(500).send({ code: 500, msg: '服务器发生错误' }); // 发生错误时，发送适当的错误信息
                } else {
                    res.send({ code: 200, msg: '添加成功' });
                }
            });
        } catch (err) {
            console.error(err);
            res.status(500).send({ code: 500, msg: '服务器发生错误' }); // 发生错误时，发送适当的错误信息
        }
    },
    async reqEditMenu(req, res) {
        let sql = "UPDATE  router_menu SET parent_id=?,path=?,icon=?,isHide=?,isKeepAlive=?,name=?,menuType=?,redirect=?,title=?,isFull=?,component=? where id=?"
        let obj = req.body
        let judgeUserNameRes2 = await utils.judgeUserName({ sql: "SELECT name FROM router_menu WHERE  id=?", sqlName: "name", name: obj.name, id: obj.id, req, res });
        if (judgeUserNameRes2 === 1) await utils.existName({ sql: "SELECT id FROM router_menu WHERE name=?", name: obj.name, res, msg: "页面名称已存在！", req });
        let meta = {};
        db.query(sql, [obj.parentId, obj.path, obj.icon, obj.isHide, obj.isKeepAlive, obj.name, obj.menuType, obj.redirect, obj.title, obj.isFull, obj.component, obj.id], (err, results) => {
            if (err) return res.cc(err)
            res.send({ code: 200, msg: '修改成功' });
        })
    },
    async reqDelMenu(req, res) {
        let sql = "DELETE FROM router_menu WHERE id=?";
        let selectSql = "SELECT id FROM router_menu WHERE parent_id=?";
        let obj = req.body;
        let result = await new Promise((resolve, reject) => {
            db.query(selectSql, obj.id, (err, results) => {
                if (err) return res.cc(err)
                resolve(results)
            })
        })
        if (result.length !== 0) return res.send({ code: 500, msg: '删除失败,请先删除子级' })
        db.query(sql, obj.id, (err, results) => {
            if (err) return res.cc(err)
            res.send({ code: 200, msg: '删除成功' })
        })
    }

}
